﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace JsonDialog
{
    public static class TextInlineParser
    {
        private static class Runtime
        {
            public static Dictionary<string, Func<List<string>, string>> Tokens = new Dictionary<string,Func<List<string>,string>>();
            public static InlineParserConfig Config = InlineParserConfig.Default;
        }

        static TextInlineParser()
        {
            Runtime.Tokens.Add("RandomFrom", Functions.RandomFrom);
            Runtime.Tokens.Add("DayQuarter", Functions.DayQuarter);
        }



        private static class Functions
        {
            public static string RandomFrom(List<string> args)
            {
                Random R = new Random();
                return args[R.Next(0, args.Count)];
            }

            public static string DayQuarter(List<string> args)
            {
                if (args.Count != 4) throw new InvalidOperationException("DayQuarter token must be used with 4 arguments");
                return args[Runtime.Config.Time.TimeOfDay.Hours / 6];
            }
        }

        public static void SetConfig(InlineParserConfig config)
        {


            
        }

        public static string ParseToken(string tokenName, List<string> tokenArgs)
        {
            return Runtime.Tokens[tokenName](tokenArgs);
        }

        public static string ParseString(string input)
        {
            List<Tuple<string,List<string>>> Tokens = new List<Tuple<string,List<string>>>();
            string result = "";
            Regex TokenMatch = new Regex(@"(?m)%(?<TokenName>\w*)(\[(?<Args>(\s*[^,]+\s*,\s*)*?[^,]+\s*)\])?");
            result = TokenMatch.Replace(input, m => ParseToken(
                m.Groups["TokenName"].Value, 
                m.Groups["Args"].Value.Split(',').Select(s => s.Trim()).ToList()));
            return result;
        }
    
    }

    
}
